package net.xuele.learn.concurrent;


import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @Author: yubo
 * @date: 15:13 2020/4/20
 * @Description: 类描述
 */

public class PatrickFutureV2<T> extends FutureTask<T> {


    private FutureListener futureListener;

    public PatrickFutureV2(PatrickCallable<T> callable) {
        super(callable);
    }

    public PatrickFutureV2(Runnable runnable, T result) {
        super(runnable, result);
    }


    void addListener(FutureListener listener) {
        this.futureListener = listener;
        if (isDone()) {
            publish();
        }

    }

    @Override
    protected void done() {
        if (this.futureListener != null) {
            publish();
        }
    }

    private void publish() {

        T t = null;
        try {
            t = get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        if (t instanceof Exception) {
            this.futureListener.onFailure((Exception) t);
        } else {
            this.futureListener.onSuccess(t);
        }
    }
}
